<template>
  <div class="create-group-wrapper" v-if="isAddGroupItemVisible">
    <el-dialog :title="titleName" :visible.sync="isAddGroupItemVisible" width="500px" :before-close="handleClose">
      <div v-show="isJoinGroup">
        <el-autocomplete
          :value-key="'groupID'"
          :debounce="500"
          size="mini"
          v-model="groupID"
          placeholder="输入群组ID搜索"
          :fetch-suggestions="searchGroupByID"
          class="group-seach-bar"
          prefix-icon="el-icon-search"
          :hide-loading="hideSearchLoading"
          @input="hideSearchLoading = false"
          @select="setGroupId"
        ></el-autocomplete>
        <el-input
          v-model="applyMessage"
          type="textarea"
          placeholder="请输入验证信息"
          style="padding-top:20px"
          maxlength="50"
          show-word-limit>
        </el-input>
      </div>
      <el-form v-show="!isJoinGroup" :model="groupInfo" ref="groupInfo" label-width="20%">
        <el-form-item label="群组ID">
          <el-input type="text" v-model="groupInfo.groupID"></el-input>
        </el-form-item>
        <el-form-item label="群名称" prop="name" :rules="[{ required: true, message: '群组名不能为空' }]">
          <el-input type="text" v-model="groupInfo.name" maxlength="10"></el-input>
        </el-form-item>
        <el-form-item label="群类型">
          <el-select v-model="groupInfo.type">
            <el-option label="Private" value="Private"></el-option>
            <el-option label="Public" value="Public"></el-option>
            <el-option label="ChatRoom" value="ChatRoom"></el-option>
            <el-option label="AVChatRoom" value="AVChatRoom"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="群头像地址">
          <el-input v-model="groupInfo.avatar" maxlength="100" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="群简介">
          <el-input type="textarea" v-model="groupInfo.introduction" maxlength="80" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="群公告">
          <el-input type="textarea" v-model="groupInfo.notification" maxlength="100" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="加群方式">
          <el-radio-group v-model="groupInfo.joinOption" :disabled="joinOptionDisabled">
            <el-radio label="FreeAccess">自由加群</el-radio>
            <el-radio label="NeedPermission">需要验证</el-radio>
            <el-radio label="DisableApply">禁止加群</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="群成员列表">
          <el-select
            v-model="groupInfo.memberList"
            default-first-option
            multiple
            filterable
            remote
            :disabled="groupInfo.type === 'AVChatRoom'"
            :remote-method="handleSearchUser"
            :loading="loading"
            placeholder="请输入群成员 userID"
          >
            <el-option v-for="item in options" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="footer">
        <div class="footer-left">
          <el-radio-group v-model="active" size="small">
            <el-radio-button label="join-group">申请加群</el-radio-button>
            <el-radio-button label="create-group">创建群组</el-radio-button>
          </el-radio-group>
        </div>
        <div class="footer-right"> 
          <el-button type="primary" @click="onSubmit('groupInfo')">确认</el-button>
          <el-button @click="handleClose">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex';

export default {
  name:'GroupAddItem',
  data() {
    return {
      active: 'join-group',
      activeName: {
        JOIN_GROUP: 'join-group',
        CREATE_GROUP: 'create-group',
      },
      groupInfo: {
        name: '',
        groupID: '',
        type: 'Private',
        avatar: '',
        introduction: '',
        notification: '',
        joinOption: 'FreeAccess',
        memberList: []
      },
      options: [],
      loading: false,
      groupID: '',
      applyMessage: '',
      hideSearchLoading: true,
      isGroupExist: false
    }
  },
  computed: {
    ...mapState({
      isAddGroupItemVisible: state => state.group.isAddGroupItemVisible
    }),
    titleName(){
      if(this.isJoinGroup){
        return '申请加群';
      } else {
        return '创建群组';
      }
    },
    joinOptionDisabled() {
      // TIM.TYPES.GRP_CHATROOM, TIM.TYPES.GRP_AVCHATROOM 类型群组的该属性不允许修改。私有群禁止申请加群，聊天室和音视频聊天室自由加入。
      return [
        this.TIM.TYPES.GRP_PRIVATE,
        this.TIM.TYPES.GRP_CHATROOM,
        this.TIM.TYPES.GRP_AVCHATROOM
      ].includes(this.groupInfo.type);
    },
    isJoinGroup(){
      return this.active === this.activeName.JOIN_GROUP;
    }
  },
  methods:{
    handleClose(){
      this.$store.commit('toggleIsAddGroupItemVisible',false);
    },
    onSubmit(ref) {
      if(this.isJoinGroup){
        if(this.isGroupExist){
          this.joinGroup();
        } else {
          this.$store.commit('showMessage', { message: '群ID无效', type: 'error'});
        }
      } else {
         // 点击提交后触发表单校验
        this.$refs[ref].validate(valid => {
          if (!valid) {
            return false;
          }
          this.createGroup();
        });
      }
    },
    searchGroupByID(queryString, callback) {
      if (queryString.trim().length > 0) {
        this.hideSearchLoading = false;
        this.tim
          .searchGroupByID(queryString)
          .then(({ data: { group } }) => {
            // 返回一个数组，里面有对象groupID:groupID
            callback([group]);
          })
          .catch(() => {
            this.isGroupExist = false;
            this.$store.commit('showMessage', { message: '没有找到该群', type: 'error'});
          })
      } else {
        this.hideSearchLoading = true;
        this.isGroupExist = false;
      }
    },
    setGroupId(){
      // 选择搜索后的群主ID才有效
      this.isGroupExist = true;
    },
    joinGroup(){
      this.$store.commit('toggleIsAddGroupItemVisible',false);
      this.$store.dispatch('joinGroup',{ groupID: this.groupID , applyMessage: this.applyMessage });
    },
    createGroup(){
      this.$store.commit('toggleIsAddGroupItemVisible',false);
      this.$store.dispatch('createGroup',this.getOptions());
    },
    getOptions() {
      // 创建群组时生成一个trtc房间id，以便在群组时进行视频通话，生成规则：7位数+当前时间戳=20位字符串，进房trtc需要转换成数字（因为这里value只能传字符串）
      let trtcRoomId = Math.floor(Math.random()*10000000).toString() +  Date.now().toString();
      let options = {
        ...this.groupInfo,
        groupCustomField: [{ key: 'trtc_roomid',value: trtcRoomId }],
        memberList: this.groupInfo.memberList.map(userID => ({ userID }))
      }
      console.log(options);
      if (['Private', 'AVChatRoom'].includes(this.groupInfo.type)) {
        delete options.joinOption;
      }
      return options;
    },
    handleSearchUser(userID) {
      if (userID !== '') {
        this.loading = true
        this.tim.getUserProfile({ userIDList: [userID] })
        .then(({ data }) => {
          this.options = data.map(item => item.userID)
          this.loading = false
        })
        .catch(error => {
          this.$store.commit('showMessage', { message: error.message , type: 'error' });
        })
      }
    }
  }
}
</script>

<style scoped>
.footer{
  padding: 30px 0;
}
.footer-left{
  float: left;
}
.footer-right{
  float: right;
}
</style>
